package net.gvne.data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import org.json.JSONTokener;

public class ConnectionInfoClient {

	public void readConnectionInfoRemote(ConnectionInfo connectionInfo) {

		HttpClient client = new DefaultHttpClient();
		String streamId = "";
		if (connectionInfo.getStreamId() != null) {
			streamId = connectionInfo.getStreamId();
		}
		HttpGet get = new HttpGet(
				"http://www.gvne.net/MyWebTvApi/api/msInfos?streamId="
						+ streamId);

		// JSONObject obj = new JSONObject();
		// obj.put("username", "un");
		// obj.put("pwd", "password");
		// obj.put("key", "123456");
		// post.setEntity(new StringEntity(obj.toString(), "UTF-8"));

		try {
			HttpResponse response = client.execute(get);
			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(response.getEntity().getContent()),
						65728);
				String jsonStr = "";
				jsonStr += reader.readLine();
				while (reader.ready()) {
					jsonStr += reader.readLine();
				}
				JSONObject responseObj = (JSONObject) new JSONTokener(jsonStr)
						.nextValue();
				JSONObject mediaServerConfig = responseObj
						.getJSONObject("mediaServerConfig");
				connectionInfo.setStreamId(responseObj.getString("streamId"));
				connectionInfo.setMsUrl(mediaServerConfig.getString("url"));
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
